#define  _CRT_SECURE_NO_WARNINGS 1
#include"DList.h"

void LTDestrot(LTNode* phead) {
	LTNode* cur = phead->next;
	while (cur->next != phead) {
		LTNode* tem = cur->next;
		LTErase(cur);
		cur = tem;
	}
	free(cur);
}

LTNode* LTFind(LTNode* phead, LTDataType x) {
	if (phead->next == phead) {
		return NULL;
	}
	LTNode* cur = phead->next;
	while (cur != phead) {
		if (cur->data == x) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void LTErase(LTNode* pos) {
	if (pos->next == pos) {
		return;
	}
	LTNode* pre = pos->prev;
	LTNode* ne = pos->next;
	pre->next = ne;
	ne->prev = pre;
	free(pos);
	pos = NULL;
}

int LTEmpty(LTNode* phead) {
	return phead->next == phead ? 1 : 0;
}

void LTprint(LTNode* phead) {
	LTNode* cur = phead->next;
	while (cur != phead) {
		printf("%d ", cur->data);
		cur = cur->next;
	}
}

LTNode* BuyNode(LTDataType x) {
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL) {
		perror("malloc fail");
		return NULL;
	}
	node->next = NULL;
	node->prev = NULL;
	node->data = x;
	return node;
}

LTNode*  LTInit() {
	LTNode* phead = BuyNode(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void LTPushBack(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* newnode = BuyNode(x);
	LTNode* tail = phead->prev;

	tail->next = newnode;
	phead->prev = newnode;
	newnode->prev = tail;
	newnode->next = phead;
}

void LTPopBack(LTNode* phead) {
	if (LTEmpty(phead)) {
		return;
	}
	//LTNode* tail = phead->prev;
	//LTNode* t_prev = tail->prev;
	//t_prev->next = phead;
	//phead->prev = t_prev;
	//free(tail);
	//tail = NULL;
	LTErase(phead->prev);
}

void LTPushFront(LTNode* phead, LTDataType x) {
	LTNode* newnode = BuyNode(x);
	newnode->next = phead->next;
	phead->next->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;
}

void LTPopFront(LTNode* phead) {
	if (LTEmpty(phead)) {
		return;
	}
	/*LTNode* cur = phead->next;
	phead->next = cur->next;
	cur->next->prev = phead;
	free(cur);
	cur = NULL;*/
	LTErase(phead->next);
}

void LTInsert(LTNode* pos, LTDataType x) {
	LTNode* prev = pos->prev;
	LTNode* newnode = BuyNode(x);

	prev->next = newnode;
	newnode->prev = prev;

	newnode->next = pos;
	pos->prev = newnode;
}


